package com.naspan.controller;

import com.naspan.common.Result;
import com.naspan.common.annotation.GlobalInterceptor;
import com.naspan.common.annotation.VerifyParam;
import com.naspan.common.constants.*;
import com.naspan.common.exception.bizExceptionHandle;
import com.naspan.entity.dto.CreateImageCode;
import com.naspan.entity.dto.RegisterSendEmailCodeDto;
import com.naspan.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class commonController {
    @Resource
    private UserService userService;

    @GetMapping("/checkCode")
    public void checkCode(HttpServletResponse response, HttpSession session, @Param("type") Integer type) throws IOException {
        CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        if (type == null || type == 0) {
            //注册的情况下
            session.setAttribute(Constants.REGISTER_CODE + "key", code);
        } else {
            //发送邮箱的情况下
            session.setAttribute(Constants.REGISTER_CODE + "mail", code);
        }
        vCode.write(response.getOutputStream());
    }

    @PostMapping("/sendEmailCode")
    @GlobalInterceptor(checkParam = true,checkLogin = false)
    public Result sendEmailCode(HttpSession session, @VerifyParam RegisterSendEmailCodeDto registerSendEmailCodeDto) {
        try {
            String checkCode = registerSendEmailCodeDto.getCheckCode();
            if (StringUtils.isEmpty(checkCode) || StringUtils.isEmpty(checkCode)) {
                throw new bizExceptionHandle("验证码参数错误1");
            }
            String code = (String) session.getAttribute(Constants.REGISTER_CODE + "mail");
            if (!checkCode.equalsIgnoreCase(code)) {
                throw new bizExceptionHandle("验证码参数错误2");
            }
            userService.sendEmailCode(registerSendEmailCodeDto);
            return Result.success("发送成功");
        } finally {
            session.removeAttribute(Constants.REGISTER_CODE + "mail");
        }
    }
}
